import { EventSourcePolyfill } from "event-source-polyfill";

let eventSource = null;
let reconnectAttempts = 0; // 重连次数

export default function subscribeWarnMsg(proxy, url) {
    if (eventSource) {
        console.log("sse已经存在：", eventSource);
        return eventSource;
    } else {
        eventSource = new EventSourcePolyfill(url, {
            heartbeatTimeout: 3 * 60 * 1000,
            headers: {
                "Content-Type": "application/json",
                Authorization: localStorage.getItem("token"),
                Accept: 'application/json',
            },
            withCredentials: true,
        })
        eventSource.onopen = function (e) {
            console.log(e, "连接刚打开时触发");
            reconnectAttempts = 0; // 重置重连次数
        };
        eventSource.onmessage = (event) => {
            console.log("收到消息内容是:", event.data)
        };
        eventSource.onerror = (event) => {
            console.error("SSE 连接出错：", event);
            eventSource.close(); // 关闭连接
            eventSource = null;
            // 自动重连逻辑
            reconnectAttempts++;
            const reconnectDelay = Math.min(30000, 1000 * Math.pow(2, reconnectAttempts)); // 计算重连延迟，最大延迟为30秒
            console.log(`将在 ${reconnectDelay} 毫秒后尝试重连...`);
            // 等待一定时间后重连
            setTimeout(() => {
                if (!eventSource) {
                    console.log("尝试重连 SSE...");
                    subscribeWarnMsg(proxy, url); // 递归调用重连
                }
            }, reconnectDelay);
        }
        return eventSource;
    }
}